import re

class Solution:
    def isValidSerialization(self, preorder: str) -> bool:
        while re.search(r"\d+,#,#", preorder):
            preorder = re.sub(r"\d+,#,#", "#", preorder)
        return preorder == "#"


a = Solution()
print(a.isValidSerialization("9,3,4,#,#,1,#,#,2,#,6,#,#"))
print(a.isValidSerialization("1,#"))
print(a.isValidSerialization("9,#,#,1"))
print(a.isValidSerialization("9,#,92,#,#"))
